<template>
  <Dialog v-model="dialogVisible" title="启用采销一码通" width="500" draggable>
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="rules" label-width="auto">
      <el-form-item label="销售所属企业" prop="saleTenantId">
        <el-select filterable v-model="formData.saleTenantId" placeholder="请选择销售所属企业" @change="tenantChange"
          class="!w-350px">
          <el-option v-for="item in tenantList" :key="item.id" :label="item.enterName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售客户企业" prop="saleCustomerId">
        <el-select filterable v-model="formData.saleCustomerId" placeholder="请选择销售客户企业"
          @visible-change="customerVisibleChange" @change="customerChange" class="!w-350px">
          <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerName"
            :value="item.customerId" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售产品" prop="saleProductIds">
        <el-select filterable multiple collapse-tags v-model="formData.saleProductIds" placeholder="请选择销售产品"
          @visible-change="productVisibleChange" class="!w-350px">
          <el-option v-for="item in productList" :key="item.productId" :label="item.productName"
            :value="item.productId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 认</el-button>
      <el-button @click="dialogVisible=false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { getTenantId, getUserId } from '@/utils/auth'
  import * as purchasePlanApi from '@/api/purchasePlan'

  const emit = defineEmits(['success'])
  const dialogVisible = ref(false)
  const formLoading = ref(false)
  const message = useMessage()
  const dialogTitle = ref()
  const result = ref({})
  const content = ref('')
  const formRef = ref()
  const formData = ref({
    userId: undefined,
    dispatchTenantId: undefined,
    purchasePlanId: undefined,
    saleTenantId: undefined,
    saleTenantName: undefined,
    saleCustomerId: undefined,
    saleCustomerName: undefined,
    saleProductIds: [],
    saleProductNames: []
  })

  const rules = reactive({
    saleTenantId: [{ required: true, message: '请选择销售所属企业', trigger: 'change' }],
    saleCustomerId: [{ required: true, message: '请选择销售客户企业', trigger: 'change' }],
    saleProductIds: [{ required: true, message: '请选择销售产品', trigger: 'change' }],
  })

  const tenantList = ref([])
  const customerList = ref([])
  const productList = ref([])

  const open = async (id) => {
    resetForm()
    formData.value.purchasePlanId = id
    formData.value.userId = getUserId()
    formData.value.dispatchTenantId = getTenantId()
    getOutTenantListByIdentityAndShare()
    dialogVisible.value = true
  }

  const resetForm = () => {
    formData.value = {
      userId: undefined,
      dispatchTenantId: undefined,
      purchasePlanId: undefined,
      saleTenantId: undefined,
      saleTenantName: undefined,
      saleCustomerId: undefined,
      saleCustomerName: undefined,
      saleProductIds: [],
      saleProductNames: []
    }
    tenantList.value = []
    customerList.value = []
    productList.value = []
  }

  const customerVisibleChange = (flag) => {
    if (flag) {
      if (!formData.value.saleTenantId) {
        message.warning('请先选择销售所属企业')
      }
    }
  }

  const productVisibleChange = (flag) => {
    if (flag) {
      if (!formData.value.saleCustomerId) {
        message.warning('请先选择销售客户企业')
      }
    }
  }

  const tenantChange = () => {
    if (formData.value.saleTenantId) {
      customerList.value = []
      productList.value = []
      formData.value.saleCustomerId = undefined
      formData.value.saleProductIds = []
      getCustomerListByIdentityAndShare()
    }
  }

  const customerChange = () => {
    if (formData.value.saleCustomerId) {
      productList.value = []
      formData.value.saleProductIds = []
      findProductByCustomerId()
    }
  }

  const getOutTenantListByIdentityAndShare = async () => {
    const res = await purchasePlanApi.getOutTenantListByIdentityAndShare({ identity: 1 })
    tenantList.value = res || []
  }

  const getCustomerListByIdentityAndShare = async () => {
    const res = await purchasePlanApi.getCustomerListByIdentityAndShare({ outTenantId: formData.value.saleTenantId, identity: 1 })
    customerList.value = res || []
  }

  const findProductByCustomerId = async () => {
    const res = await purchasePlanApi.findProductByCustomerId({ customerId: formData.value.saleCustomerId })
    productList.value = res || []
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    try {
      formLoading.value = true
      formData.value.saleTenantName = tenantList.value.find(e => e.id === formData.value.saleTenantId)?.enterName
      formData.value.saleCustomerName = customerList.value.find(e => e.customerId === formData.value.saleCustomerId)?.customerName
      formData.value.saleProductNames = productList.value.filter(e => formData.value.saleProductIds.includes(e.productId)).map(m => m.productName)
      await purchasePlanApi.createDispatchPurchaseSalePlan(formData.value)
      message.success('启用一码通成功')
      emit('success')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }

  defineExpose({ open })
</script>
<style lang="scss" scoped>
  .custom-dialog .el-dialog__body {
    color: #303133;
    padding: 20px 24px !important;
  }
</style>